<?php

use App\Admin\Controller\Base\CommonController;
use App\Admin\Controller\Base\SuperConfigController;
use App\Admin\Service\Base\SuperConfigService;
use App\Common\Enums\Base\SuperConfigEnumType;
use App\Common\Model\Base\SuperConfig;
use App\Common\Util\TP;
use Plugins\Dev\Admin\Service\DevAuxService;
use Sc\Util\HtmlStructure\Form;
use Sc\Util\HtmlStructure\Form\FormItem;
use Sc\Util\HtmlStructure\Html\Html;

/** @var SuperConfig $superConfig */

$uploadUrl = TP::route()->to([CommonController::class, 'upload']);
$froalaUploadUrl = TP::route()->to([CommonController::class, 'froalaUpload']);

Html::create('配置');

$form = Form::create('config')->config('label-width', '120px');

$supportForm = array_column(SuperConfigService::supportForm(), 'value');

$form->addFormItems(FormItem::hidden('id', 'ID')->default($superConfig->id),);

if ($superConfig->type === SuperConfigEnumType::SingleItemGroup->value) {
    foreach ($superConfig->config_info as $value) {
        $formType = $value['formType'];
        if (empty($formType) || !in_array($formType, $supportForm)) {
            continue;
        }
        if ($formType === 'image' || $formType === 'images') {
            $formType = 'upload';
        }

        $formItem = FormItem::{$formType}($value['field'], $value['title']);

        if ($value['extra'] && method_exists($formItem, 'options')) {
            if (count($value['extra']) == 1) {
                if (str_contains($value['extra'][0], ':') && str_contains($value['extra'][0], '=')) {
                    list($tableName, $fields) = explode(':', $value['extra'][0]);
                    $where = "";
                    if (str_contains($fields, ';')) {
                        list($fields, $where) = explode(';', $fields);
                    }
                    list($key, $label) = explode('=', $fields);

                    $optionsQuery = \think\facade\Db::name($tableName);
                    if ($where) {
                        array_map(function ($v) use ($optionsQuery){
                            list($k, $v) = explode('=', $v);
                            str_contains($v, ',')
                                ? $optionsQuery->whereIn($k, explode(',', $v))
                                : $optionsQuery->where($k, $v);
                        }, explode('&', $where));
                    }

                    $options = $optionsQuery->whereNull('delete_time')->field("$key as value, $label as label")->select()->toArray();
                }else if(str_contains($value['extra'][0], ':')){
                    list($configKey, $showField) = explode(':', $value['extra'][0]);
                    $options = \App\Common\Service\SuperConfigService::get($configKey);
                    $options = array_map(fn($v) => ['label' => $v[$showField], 'value' => $v['cid']], $options);
                }else{
                    $options = \App\Common\Service\SuperConfigService::get($value['extra'][0]);
                }
                $optionsVar = "System" . substr(md5($value['extra'][0]), 0, 10);
            }else{
                $options = array_map(function ($v) {
                    return array_combine(['value', 'label'], explode('=', $v));
                }, $value['extra']);
                $optionsVar = $value['field'] . '_options';
            }

            $formItem->setOptionsVarName($optionsVar)->options($options);
        }

        if ($formItem instanceof Form\FormItemUpload) {
            $formItem->setUploadUrl($uploadUrl);
        }

        if ($formItem instanceof Form\FormItemEditor) {
            $formItem->setUploadUrl($froalaUploadUrl);
        }
        if ($value['formType'] === 'image') {
            $formItem->toImage();
        }elseif ($value['formType'] === 'images'){
            $formItem->toImage(true);
        }

        $form->addFormItems($formItem);
    }
}else if($superConfig->type === SuperConfigEnumType::Array->value){
    $form->addFormItems(
        FormItem::table('content')->addItems(
            FormItem::text('value', '配置项')
        )
    );
}else{
    $form->addFormItems(
        FormItem::table('content')->addItems(
            FormItem::text('key', 'Key值'),
            FormItem::text('value', 'Value值'),
        )
    );
}

$form->addFormItems(
    TP::request()->get('_tab')
        ? FormItem::submit()->submitUrl(TP::route()->to([SuperConfigController::class, 'updateBaseConfig'])->url(),)
            ->success("this.\$message.success('更新成功')", true)
        : FormItem::submit()->successClose('parent')->submitUrl(TP::route()->to([SuperConfigController::class, 'updateBaseConfig'])->url(),
    ),
);

$superConfig->config_value and $form->setData(array_merge(
    $superConfig->config_value,
    [
        'id' => $superConfig->id
    ]
));

return $form->render();